package com.sun.test;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * @author shkstart
 * @create 2021-09-21 13:19
 */
public class Jwt {

    public static void main(String[] args) {
        String token = getToken();
        System.out.println(token);
        prise();
    }

    /**
     * 生成token
     * @return
     */
    public static String getToken(){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,90);
        String token= JWT.create()
                .withClaim("username","张三")//设置自定义用户名
                .withExpiresAt(instance.getTime())//设置过期时间
                .sign(Algorithm.HMAC256("token!Q2W#E$RW"));////设置签名 保密 复杂
        return token;
    }
    /**
     * 根据令牌和签名解析数据
     */
    public static void prise(){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256("token!Q2W#E$RW")).build();
        DecodedJWT decodedJWT = verifier.verify(getToken());
        System.out.println("用户名username:"+decodedJWT.getClaim("username").asString());
        System.out.println("过期时间:expire:"+decodedJWT.getExpiresAt());
    }
}
